using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Reflection;
using System.ServiceModel;
using System.Workflow.Activities;
using System.Workflow.Runtime;
using SLS.ExClassLib.Event;
using SLS.ExClassLib.Events;
using SLS.ExClassLib.Message;
using SLS.ExClassLib.Contract;
using SLS.Base;
using SLS.Core.HLASimu;
namespace LanSunStudio.Service.WorkFlowService
{
    /// <summary>
    /// Beer Service Implementation
    /// </summary>
    /// <remarks>
    /// Single is the default concurrency mode, but it never hurts to be explicit.
    /// Note the single threading model still functions properly with use of one way methods for callbacks 
    /// since they are marked as one way on the contract.
    /// </remarks>
    [ServiceBehavior(
        ConcurrencyMode = ConcurrencyMode.Single,
        InstanceContextMode = InstanceContextMode.Single)]
    partial class WorkFlowCenterService : SLBC, IWorkFlowCenter
    {
        string filepath=System.IO.Directory.GetCurrentDirectory() + @"\WorkFlow\";
        public Assembly AsmWFEdit = Assembly.LoadFrom(System.IO.Directory.GetCurrentDirectory() + @"\WFActivity.dll");
        string strConn = @"Data Source=SUNLIGHT\LANSUNERP;Initial Catalog=WrokFlowService;Persist Security Info=True;User ID=LanSunERP2010;Password=LanSunERP2010";
        public SqlConnection sqlConnection;
        private static Dictionary<string, IWorkFlowCenterCallBack> m_AgentcallbackList = new Dictionary<string, IWorkFlowCenterCallBack>();
        public Dictionary<Guid, StateMachineWorkflowInstance> WorkFlowList = new Dictionary<Guid, StateMachineWorkflowInstance>();
        public StateMachineWorkflowInstance m_StateMachineWFInstance;
        private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        string m_CenterUICallBackPath = "";
        private Guid CenterWFInstance_ID;
        Guid WFInstance_ID;
        WorkflowInstance wfinstance; 
        Dictionary<string, object> WFParams; 
        public ExMessagePool MessagePool = new ExMessagePool();
        IWorkFlowCenterCallBack AgentCallback;
        public WFServiceFederate fed;
        public WorkFlowCenterService()
        {
            
            try
            {
                sqlConnection = new SqlConnection(strConn);
                flagJoinWFSRVFederate = true;
                Address = "WFServiceFederate";
                StartFedrate();
                MessageEx msg = new MessageEx();
                msg.Address = Address;
                fed = (WFServiceFederate)EventDispatcher.Instance.GetFederate("WFServiceFederate", msg, null);
                fed.doc = this;

                /*
                waitHandle = new AutoResetEvent(false);
                workflowruntime = new WorkflowRuntime();

                WorkflowRuntimeSection config;
                config = ConfigurationManager.GetSection("WorkflowWithTracking") as WorkflowRuntimeSection;

                //string strConn = config.CommonParameters["ConnectionString"].Value;
                string strConn = @"Data Source=SUNLIGHT\LANSUNERP;Initial Catalog=WrokFlowService;Persist Security Info=True;User ID=LanSunERP2010;Password=LanSunERP2010";
                //workflowruntime.AddService(new SqlTrackingService(connectionString));
                //workflowruntime = new WorkflowRuntime("DefaultRuntime");
                SqlTrackingService sts = new SqlTrackingService(strConn);
                sts.IsTransactional = false;
                workflowruntime.AddService(sts);

                workflowruntime.AddService(new SqlWorkflowPersistenceService(strConn));
                workflowruntime.AddService(new DefaultWorkflowSchedulerService(2000));

                DefaultWorkflowSchedulerService scheduler =
                    workflowruntime.GetService<DefaultWorkflowSchedulerService>();

                //workflowruntime.AddService(new CallWorkflowService());
                //workflowruntime.AddService(new CallWorkflowWorkflowLoaderService());

                ExDataExchService = new ExternalDataExchangeService();
                workflowruntime.AddService(ExDataExchService);
                ExDataExchService.AddService(this);
                workflowruntime.WorkflowCreated += new EventHandler<WorkflowEventArgs>(workflowruntime_WorkflowCreated);
                workflowruntime.WorkflowCompleted += new EventHandler<WorkflowCompletedEventArgs>(workflowruntime_WorkflowCompleted);
                */

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

   
        private void workflowruntime_WorkflowCreated(object sender, WorkflowEventArgs e)
        {
            
        }
        private void workflowruntime_WorkflowCompleted(object sender, WorkflowCompletedEventArgs e)
        {
            try
            {
                Guid wfID = e.WorkflowInstance.InstanceId;
                if (WorkFlowList.ContainsKey(wfID))
                {
                    WorkFlowList.Remove(wfID);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
             
        }

      
 
        public void WFService(MessageEx msg)
        {
            try
            {
                string WFType = msg.JobContent;
                if (WFType == "WFEditCenterWorkFlow")
                { 
                    AgentCallback = OperationContext.Current.GetCallbackChannel<IWorkFlowCenterCallBack>();
                    RegisterCallBackPath(AgentCallback, msg, true); 
                }
                EventDispatcher.Instance.Publish(msg, null, EventType.UI2WC);
                //EventDispatcher.Instance.RECVUI2WFMessage(msg);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        }

        public override void ProcessWFMessage(MessageEx msg)
        {
            string JobType = msg.JobType;
            try
            {
                if (JobType == "UI2WF"
                    || JobType == "UI2WC")
                {
                    ReceiveMessage(msg);
                    return;
                }
                SendMessage(msg);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        } 
    }
}
